package com.learn2.other;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Author:Mark
 * @Description:
 * @Date: Created on 16:12 2018-11-15
 * @Modify by:
 */
@ControllerAdvice   //组合了component注解，自动注册成为sprig的bean
public class ExceptionHandlerAdvice {

  @ExceptionHandler(value = Exception.class)    //在此处定义全局的异常处理，value的值定义拦截的异常类型
  public ModelAndView exception(Exception ex, WebRequest request){
    ModelAndView modelAndView=new ModelAndView("error");
    modelAndView.addObject("errorMessage",ex.getMessage());
    return modelAndView;

  }

  @ModelAttribute     //将键值对添加到全局
  public void addAttributes(Model model){
    model.addAttribute("msg","额外信息");
  }

  @InitBinder
  public void ininBinder(WebDataBinder webDataBinder){
    webDataBinder.setDisallowedFields("id");
  }

}
